package com.gnrsoft.fastdfs.service.impl;

import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gnrsoft.fastdfs.dto.ResultDto;
import com.gnrsoft.fastdfs.dto.UploadFileDto;
import com.gnrsoft.fastdfs.exception.AppException;
import com.gnrsoft.fastdfs.exception.ERRORS;
import com.gnrsoft.fastdfs.pool.FastDfsUtil;
import com.gnrsoft.fastdfs.service.CommonUploadFileService;
import com.gnrsoft.fastdfs.util.CommonUtils;

/**
 * 公共上传文件服务接口实现类
 * 
 * @author mr_smile
 * 
 */
@Service("commonUploadFileService")
public class CommonUploadFileServiceImpl implements CommonUploadFileService {

	/** 日志 */
	private final Logger log = Logger
			.getLogger(CommonUploadFileServiceImpl.class);

	/** fastdfs工具类 */
	@Autowired
	private FastDfsUtil fastDfsUtil;

	/**
	 * 上传文件
	 * 
	 * @param uploadFileDto
	 *            上传文件dto
	 * @return
	 */
	@Override
	public ResultDto uploadFile(UploadFileDto uploadFileDto)
			throws AppException {

		/** 日志标识 */
		String logId = UUID.randomUUID().toString();
		log.info("[上传文件（uploadFile）][" + logId + "][prams：uploadFileDto="
				+ uploadFileDto.toString() + "]");

		try {

			/** 判断参数是否为空 */
			vlidParamIsNull(uploadFileDto, logId);

			/** 调用工具类上传 */
			ResultDto result = fastDfsUtil.upload(uploadFileDto);

			log.info("[上传文件（uploadFile)-返回结果][" + logId
					+ "][results：resultDto=" + result.toString() + "]");

			return result;

		} catch (AppException e) {

			log.error("[上传文件（uploadFile)][" + logId + "][异常：" + e + "]");
			throw e;

		}

	}

	/**
	 * 删除fastdfs服务器中文件
	 * 
	 * @param filePath
	 *            文件远程地址
	 * @return
	 */
	public void deleteFile(String filePath) throws AppException {

		/** 日志标识 */
		String logId = UUID.randomUUID().toString();
		log.info("[ 删除文件（deleteFile）][" + logId + "][parms：filePath="
				+ filePath + "]");
		try {
			if (StringUtils.isBlank(filePath)) {
				throw ERRORS.PARAMETER_IS_NULL.ERROR();
			}

			/** 解析文件路径 */
			String[] results = CommonUtils.parseFilePath(filePath, logId);

			/** 删除文件 */
			fastDfsUtil.deleteFile(results[0], results[1]);

		} catch (AppException e) {
			log.error("[ 删除文件（deleteFile）][" + logId + "][异常：" + e + "]");
			throw e;

		}
	}

	/**
	 * 
	 * @Description: 验证上传方法参数是否为空
	 * @param uploadFileDto
	 * @param logId
	 * 
	 */
	public void vlidParamIsNull(UploadFileDto uploadFileDto, String logId)
			throws AppException {

		log.info("[验证上传方法参数是否为空（vlidParamIsNull）][" + logId
				+ "][prams：uploadFileDto=" + uploadFileDto.toString() + "]");

		if (null == uploadFileDto || uploadFileDto.getFileBytes() == null
				|| null == uploadFileDto.getFileExtName()) {
			throw ERRORS.PARAMETER_IS_NULL.ERROR();
		}

	}
}
